package com.client.window;

import com.client.service.OICQClient;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

/**
 * @Author e4glet
 * 2025年3月5日
 * */

// 登录窗口
public class LoginWindow extends JFrame {
    private JTextField emailField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private OICQClient client;

    // 登录窗口构造器用于初始化
    public LoginWindow(OICQClient client) {
        this.client = client;
        setTitle("登录");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        add(panel);
        placeComponents(panel);
        setResizable(false); // 设置窗口不可调整大小
        setVisible(true);
    }

    // 添加登录窗口界面组件
    private void placeComponents(JPanel panel) {
        panel.setLayout(null);

        JLabel accountLabel = new JLabel("QQ号/邮箱:");
        accountLabel.setBounds(10, 20, 80, 25);
        panel.add(accountLabel);

        emailField = new JTextField(20);
        emailField.setBounds(100, 20, 165, 25);
        panel.add(emailField);

        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setBounds(10, 50, 80, 25);
        panel.add(passwordLabel);

        passwordField = new JPasswordField(20);
        passwordField.setBounds(100, 50, 165, 25);
        panel.add(passwordField);

        loginButton = new JButton("登录");
        loginButton.setBounds(10, 80, 80, 25);
        panel.add(loginButton);

        registerButton = new JButton("注册");
        registerButton.setBounds(180, 80, 80, 25);
        panel.add(registerButton);

        // 添加登录按钮监听器
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String email = emailField.getText();
                String password = new String(passwordField.getPassword());

                try {
                    if (client.loginUser(email, password)) {
                        JOptionPane.showMessageDialog(null, "登录成功");
                        new MainWindow(client); // 传递client实例
                        dispose();
                    } else {
                        JOptionPane.showMessageDialog(null, "登录失败");
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, "登录失败");
                }
            }
        });

        // 添加注册按钮监听器
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new RegisterWindow(client);
            }
        });
    }
}
